<template>
  <!-- 导航栏 -->
  <van-nav-bar title="缴费" left-text="返回" left-arrow @click-left="back">
    
	<template #right>
	  <van-icon name="ellipsis" size="18" @click="showShare = true"/>
			<van-share-sheet
			  v-model:show="showShare"
			  title="立即分享给好友"
			  :options="shareOptions"
			  @select="onShareSelect"
			/>
	</template>
	
  </van-nav-bar>

  <!-- 用户信息栏 -->
  <van-nav-bar>
    <template #left>
      <div class="user-info">
        <van-icon name="user-circle-o" size="18" />
        <span>{{ currentUser }}</span>
      </div>
    </template>
    <van-cell>当前就诊人: {{ defaultPatientName }}</van-cell>
  </van-nav-bar>

  <!-- 缴费内容 -->
  <van-tabs v-model:active="active" animated swipeable>
    <!-- 待支付 -->
    <van-tab title="待支付">
      <van-empty v-if="unpaidList.length === 0 && !loading" description="暂无待支付订单" />
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="loadUnpaid"
      >
        <div class="payment-card" v-for="item in unpaidList" :key="item.record_id">
          <div class="payment-header">
            <span class="patient-name">{{ getPatientName(item) }}</span>
            <van-tag :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </van-tag>
          </div>

          <div class="payment-content">
            <div class="payment-row">
              <span>应收金额</span>
              <span class="amount">¥{{ item.amount?.toFixed(2) || '0.00' }}</span>
            </div>
            <div class="payment-row">
              <span>实收金额</span>
              <span class="amount">¥{{ (item.paid_amount || 0)?.toFixed(2) }}</span>
            </div>
            <div class="payment-row">
              <span>欠费金额</span>
              <span class="amount unpaid">¥{{ (item.amount - (item.paid_amount || 0))?.toFixed(2) }}</span>
            </div>
            <div class="payment-row">
              <span>创建时间</span>
              <span class="time">{{ formatDate(item.create_time) }}</span>
            </div>
          </div>

          <div class="payment-footer">
            <van-button type="primary" size="small" @click="handlePay(item)">
              {{ item.status === 2 ? '重新支付' : '立即支付' }}
            </van-button>
            <van-button plain size="small" @click="showDetail(item)">详情</van-button>
          </div>
        </div>
      </van-list>
    </van-tab>

    <!-- 历史记录 -->
    <van-tab title="历史记录">
      <van-empty v-if="historyList.length === 0 && !historyLoading" description="暂无支付记录" />
      <van-list
        v-model:loading="historyLoading"
        :finished="historyFinished"
        finished-text="没有更多了"
        @load="loadHistory"
      >
        <div class="payment-card" v-for="item in historyList" :key="item.record_id">
          <div class="payment-header">
            <span class="patient-name">{{ getPatientName(item) }}</span>
            <van-tag :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </van-tag>
          </div>

          <div class="payment-content">
            <div class="payment-row">
              <span>应收金额</span>
              <span class="amount">¥{{ item.amount?.toFixed(2) || '0.00' }}</span>
            </div>
            <div class="payment-row">
              <span>实收金额</span>
              <span class="amount">¥{{ (item.paid_amount || 0)?.toFixed(2) }}</span>
            </div>
            <div class="payment-row">
              <span>支付时间</span>
              <span class="time">{{ formatDate(item.pay_time) || '-' }}</span>
            </div>
            <div class="payment-row" v-if="item.status === 1">
              <span>支付方式</span>
              <span class="time">{{ getPayType(item.pay_type) }}</span>
            </div>
            <div class="payment-row" v-if="item.status === 2">
              <span>失败原因</span>
              <span class="time">{{ item.fail_reason || '未知原因' }}</span>
            </div>
          </div>

          <div class="payment-footer">
            <van-button plain size="small" @click="showDetail(item)">查看详情</van-button>
            <van-button v-if="item.status === 1" plain size="small" @click="showReceipt(item)">电子收据</van-button>
          </div>
        </div>
      </van-list>
    </van-tab>
  </van-tabs>

  <!-- 支付弹窗 -->
  <van-action-sheet v-model:show="showPayPanel" title="选择支付方式">
    <div class="pay-methods">
      <van-radio-group v-model="selectedPayMethod">
        <van-cell-group>
          <van-cell clickable @click="selectedPayMethod = 'wechat'">
            <template #title>
              <van-icon name="wechat" color="#07C160" size="20" />
              <span class="method-name">微信支付</span>
            </template>
            <template #right-icon>
              <van-radio name="wechat" />
            </template>
          </van-cell>
          <van-cell clickable @click="selectedPayMethod = 'alipay'">
            <template #title>
              <van-icon name="alipay" color="#1677FF" size="20" />
              <span class="method-name">支付宝支付</span>
            </template>
            <template #right-icon>
              <van-radio name="alipay" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>

      <div class="pay-actions">
        <van-button type="primary" block round @click="confirmPay" :disabled="!selectedPayMethod" :loading="payLoading">
          确认支付 ¥{{ currentPayment?.amount?.toFixed(2) || '0.00' }}
        </van-button>
      </div>
    </div>
  </van-action-sheet>

  <!-- 详情弹窗 -->
  <van-popup v-model:show="showDetailPanel" round position="bottom" :style="{ height: '70%' }">
    <div class="detail-container">
      <div class="detail-header">
        <h3>缴费详情</h3>
        <van-icon name="cross" @click="showDetailPanel = false" />
      </div>
      
      <div class="detail-content">
        <div class="detail-item">
          <span>患者姓名</span>
          <span>{{ getPatientName(currentDetail) || '-' }}</span>
        </div>
        <div class="detail-item">
          <span>缴费单号</span>
          <span>{{ currentDetail?.pay_no || '-' }}</span>
        </div>
        <div class="detail-item">
          <span>应收金额</span>
          <span>¥{{ currentDetail?.amount?.toFixed(2) || '0.00' }}</span>
        </div>
        <div class="detail-item">
          <span>实收金额</span>
          <span>¥{{ (currentDetail?.paid_amount || 0)?.toFixed(2) }}</span>
        </div>
        <div class="detail-item">
          <span>欠费金额</span>
          <span>¥{{ ((currentDetail?.amount || 0) - (currentDetail?.paid_amount || 0))?.toFixed(2) }}</span>
        </div>
        <div class="detail-item">
          <span>创建时间</span>
          <span>{{ formatDate(currentDetail?.create_time) || '-' }}</span>
        </div>
        <div class="detail-item">
          <span>支付时间</span>
          <span>{{ formatDate(currentDetail?.pay_time) || '-' }}</span>
        </div>
        <div class="detail-item" v-if="currentDetail?.status === 1">
          <span>支付方式</span>
          <span>{{ getPayType(currentDetail?.pay_type) || '-' }}</span>
        </div>
        <div class="detail-item" v-if="currentDetail?.status === 2">
          <span>失败原因</span>
          <span>{{ currentDetail?.fail_reason || '未知原因' }}</span>
        </div>
        <div class="detail-item">
          <span>状态</span>
          <span>
            <van-tag :class="currentDetail ? getStatusClass(currentDetail.status) : ''">
              {{ currentDetail ? getStatusText(currentDetail.status) : '' }}
            </van-tag>
          </span>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showNotify, showDialog, showFailToast } from 'vant';
import axios from 'axios';
import { useUserStore } from '../stores/user.js';


const router = useRouter();
const userStore = useUserStore();
const active = ref(0);

/* 用户相关 */
const currentUser = ref(localStorage.getItem('username') || '未登录用户');
const userId = ref(localStorage.getItem('userId'));

/* 列表数据 */
// 获取默认就诊人信息
const defaultPatient = computed(() => userStore.getDefaultPatient());
const defaultPatientName = computed(() => defaultPatient.value?.name || '未设置默认就诊人');
const defaultPatientId = computed(() => defaultPatient.value?.patient_id || null);

/* 列表数据 */
const unpaidList = ref([]);
const historyList = ref([]);

/* 加载状态 */
const loading = ref(false);
const finished = ref(false);
const historyLoading = ref(false);
const historyFinished = ref(false);
const payLoading = ref(false);

/* 弹窗控制 */
const showPayPanel = ref(false);
const selectedPayMethod = ref('');
const currentPayment = ref(null);
const showDetailPanel = ref(false);
const currentDetail = ref(null);
const showShare = ref(false);
const options = [
  { name: '微信', icon: 'wechat' },
  { name: '支付宝', icon: 'alipay' },
  { name: 'QQ', icon: 'qq' },
];

/* 工具函数 */
const getPatientName = (item) => {
  // 优先使用默认就诊人名称
  if (defaultPatient.value) {
    return defaultPatient.value.name;
  }
  return item?.username || item?.patient?.name || '未知患者';
};

const formatDate = (d) => d ? new Date(d).toLocaleString() : '-';
const getPayType = (t) => ({ 1: '微信支付', 2: '支付宝支付', 3: '银行卡支付' }[t] || '未知');

// 状态文本映射
const getStatusText = (status) => {
  const statusMap = {
    0: '处理中',
    1: '支付成功',
    2: '支付失败'
  };
  return statusMap[status] || '未知状态';
};

// 状态样式类映射
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-pending', // 待支付/处理中 - 蓝色
    1: 'status-success', // 支付成功 - 绿色
    2: 'status-failed'   // 支付失败 - 红色
  };
  return classMap[status] || '';
};

/* 接口调用 */
const loadUnpaid = async () => {
  if (!defaultPatientId.value) {
    showFailToast('请先设置默认就诊人');
    return;
  }
  loading.value = true;
  try {
    const { data } = await axios.get(`/api/v1/payment/pending/${defaultPatientId.value}`);
    if (data.code === 0) unpaidList.value = data.data || [];
  } finally { loading.value = false; finished.value = true; }
};

const loadHistory = async () => {
  if (!defaultPatientId.value) {
    showFailToast('请先设置默认就诊人');
    return;
  }
  historyLoading.value = true;
  try {
    const { data } = await axios.get(`/api/v1/payment/record/${defaultPatientId.value}`);
    if (data.code === 0) historyList.value = data.data || [];
  } finally { historyLoading.value = false; historyFinished.value = true; }
};

/* 业务交互 */
const handlePay = (item) => { currentPayment.value = item; showPayPanel.value = true; };
const showDetail = (item) => { currentDetail.value = item; showDetailPanel.value = true; };
const showReceipt = (item) => {
  // 电子收据逻辑
  showNotify({ type: 'info', message: '电子收据功能待实现' });
};

const confirmPay = async () => {
  if (!selectedPayMethod.value) return showFailToast('请选择支付方式');
  try {
    await showDialog({ title: '确认支付', message: `确定支付 ¥${currentPayment.value.amount?.toFixed(2)} 吗？` });
    payLoading.value = true;
    const { data } = await axios.put(`/api/v1/payment/markPaid/${currentPayment.value.record_id}`, {
      pay_type: selectedPayMethod.value === 'wechat' ? 1 : 2,
      status: 0
    });
    if (data.code === 0) {
      showNotify({ type: 'success', message: '支付成功' });
      showPayPanel.value = false;
      loadUnpaid(); loadHistory(); // 重新拉取
    } else {
      showFailToast(data.message || '支付失败');
    }
  } finally { payLoading.value = false; selectedPayMethod.value = ''; }
};


const back = () => router.go(-1);

onMounted(() => {
  if (!userId.value) { 
    showFailToast('请先登录'); 
    router.push('/login'); 
    return; 
  }
  
  // 检查是否有默认就诊人
  if (!defaultPatient.value) {
    showFailToast('请先设置默认就诊人');
    router.push('/patientManagement');
    return;
  }
  
  loadUnpaid(); 
  loadHistory();
});
</script>



<style scoped>
/* 状态颜色样式 */
.status-success {
  background-color: #07C160 !important;
  color: white !important;
}

.status-failed {
  background-color: #ee0a24 !important;
  color: white !important;
}

.status-pending {
  background-color: #1677FF !important;
  color: white !important;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.payment-card {
  margin: 12px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f5f5f5;
}

.patient-name {
  font-size: 16px;
  font-weight: 500;
}

.payment-content {
  margin-bottom: 16px;
}

.payment-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.amount {
  font-weight: 500;
  color: #ee0a24;
}

.unpaid {
  color: #ff976a;
}

.time {
  color: #969799;
}

.payment-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.detail-container {
  padding: 16px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.detail-item span:first-child {
  color: #969799;
}

.method-name {
  margin-left: 8px;
}

.pay-actions {
  padding: 16px;
}

.pay-methods {
  padding-bottom: 20px;
}
</style>
